import { message, modal } from '@/utils/antdHelper'
import { RESULT_CODE } from '@/utils/constants'

import { getBasicFn } from './dvaUtil'

let confirmFlag = false

const modalCloseFn = () => {
  confirmFlag = false
}

/**
 * 异常弹框
 * @param {import("antd/es/modal").ModalFuncProps} props
 */
const openError = props => {
  if (!confirmFlag) {
    confirmFlag = true
    modal.error({
      maskClosable: false,
      onCancel: modalCloseFn,
      onOk: modalCloseFn,
      closable: true,
      zIndex: 9999, // 根据业务需要可能设置zIndex 到时全局的弹框被遮照 因此加大全局的zIndex
      ...props,
    })
  }
}

/**
 * 警告弹框
 * @param {import("antd/es/modal").ModalFuncProps} props
 */
const openWarning = props => {
  if (!confirmFlag) {
    confirmFlag = true
    modal.warning({
      maskClosable: false,
      onCancel: modalCloseFn,
      onOk: modalCloseFn,
      zIndex: 9999, // 根据业务需要可能设置zIndex 到时全局的弹框被遮照 因此加大全局的zIndex
      ...props,
    })
  }
}

const onAppError = (error = {}) => {
  console.error(error)
  try {
    error.preventDefault && error.preventDefault()
    if (!error.stack) {
      const { status } = error
      if (status >= 200 && status < 300) {
        const data = error.data
        const { code } = data
        if (code === RESULT_CODE.LOGIN_DISABLED_CODE) {
          message.error('该账号已被禁用，请联系管理员')
          return
        }
        if (code === RESULT_CODE.REQUEST_TOKEN_OVERDUE_CODE) {
          openWarning({
            title: '登录超时',
            content: '当前用户登录已失效, 点击确定以重新登录',
            onOk: () => {
              const { toAction } = getBasicFn({ namespace: 'app' })
              toAction('logout')
            },
          })
          return
        }
        if (code !== RESULT_CODE.REQUEST_SUCCESS_CODE) {
          openError({ content: data.message, title: '操作失败' })
        }
      } else if (!status) {
        openWarning({ content: '网络开小差了, 请检查网络环境' })
      } else {
        openWarning({ content: '系统异常' })
      }
    } else {
      if (error.code === 'ERR_CANCELED') {
        return
      }
      if (error.message) {
        openError({ content: error.message })
        return
      }
      openError({ content: '系统异常' })
    }
  } catch (e) {
    console.error(e)
  }
}

export default onAppError
